from flask import Flask, request, redirect, url_for, render_template, flash
import mysql.connector
from docx import Document
import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'docx'}
app.secret_key = 'some_secret_key'  # 用于闪存消息


# 允许的文件类型
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']


# 提取题目和答案
def extract_questions(file_path, question_type):
    document = Document(file_path)
    questions = []
    current_question = None

    for para in document.paragraphs:
        text = para.text.strip()

        if question_type == 'questionsxuanze':  # 选择题
            if text.startswith("Q:"):
                if current_question:
                    questions.append(current_question)
                current_question = {
                    'text': text[2:].strip(),
                    'options': {'A': None, 'B': None, 'C': None, 'D': None},
                    'correct_answer': None
                }
            elif text.startswith("A:") or text.startswith("B:") or text.startswith("C:") or text.startswith("D:"):
                if current_question:
                    current_question['options'][text[0]] = text[2:].strip()
            elif text.startswith("Answer:"):
                if current_question:
                    current_question['correct_answer'] = text[7:].strip()
            if current_question and len(current_question['options']) == 4:
                questions.append(current_question)

        elif question_type == 'question2':  # 判断题
            if text.startswith("Q:"):
                if current_question:
                    questions.append(current_question)
                current_question = {
                    'text': text[2:].strip(),
                    'correct_answer': None
                }
            elif text.startswith("答案:"):
                if current_question:
                    answer_text = text[3:].strip()
                    if answer_text in ['对', '错']:
                        current_question['correct_answer'] = answer_text

        elif question_type == 'questions':  # 主观题
            if text and (text[0].isdigit() and text[1] == '.'):
                if current_question:
                    questions.append(current_question)
                current_question = {'text': text, 'answers': []}
            elif text:
                if current_question:
                    current_question['answers'].append(text)

    if current_question:
        questions.append(current_question)

    return questions


# 将题目插入到数据库
def insert_questions(exam_name, questions, question_type):
    conn = mysql.connector.connect(
        host="localhost",
        user="root",
        password="09876",  # 替换为实际的数据库密码
        database="school",
        charset='utf8mb4'
    )
    cursor = conn.cursor()

    try:
        # 插入试卷信息
        sql = "INSERT INTO exams (name) VALUES (%s)"
        cursor.execute(sql, (exam_name,))
        exam_id = cursor.lastrowid

        for question in questions:
            if question_type == 'questionsxuanze':  # 选择题
                sql = """
                INSERT INTO questionsxuanze (exam_id, question_text, a, b, c, d, correct_answer)
                VALUES (%s, %s, %s, %s, %s, %s, %s)
                """
                values = (
                    exam_id, question['text'],
                    question['options']['A'], question['options']['B'],
                    question['options']['C'], question['options']['D'],
                    question['correct_answer']
                )
            elif question_type == 'question2':  # 判断题
                sql = """
                INSERT INTO question2 (exam_id, question_text, correct_answer)
                VALUES (%s, %s, %s)
                """
                values = (exam_id, question['text'], question['correct_answer'])
            elif question_type == 'questions':  # 主观题
                sql = """
                INSERT INTO questions_and_answers (exam_name, question_text, answer_text)
                VALUES (%s, %s, %s)
                """
                for answer in question['answers']:
                    values = (exam_name, question['text'], answer)
                    cursor.execute(sql, values)
                    continue

            cursor.execute(sql, values)

        conn.commit()
    except mysql.connector.Error as err:
        print(f"Error: {err}")
        conn.rollback()
    finally:
        cursor.close()
        conn.close()


@app.route('/')
def index():
    return render_template('upload.html')


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files or request.files['file'].filename == '':
        return '没有选择文件'

    file = request.files['file']
    question_type = request.form['question_type']

    if file and allowed_file(file.filename):
        filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filename)

        # 调试信息
        print(f"文件已保存到: {filename}")

        # 检查文件是否正确保存
        if not os.path.exists(filename):
            return '文件保存失败'

        try:
            questions = extract_questions(filename, question_type)
            print(f"提取的问题: {questions}")
        except Exception as e:
            print(f"提取问题时发生错误: {e}")
            return '提取问题失败'

        try:
            insert_questions('Sample Exam', questions, question_type)
        except Exception as e:
            print(f"插入问题时发生错误: {e}")
            return '插入问题失败'

        return redirect(url_for('upload_success'))

    return '文件格式不正确'


@app.route('/upload_success')
def upload_success():
    return render_template('success.html')  # 使用模板渲染成功页面



if __name__ == '__main__':
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])
    app.run(host='0.0.0.0', port=5000, debug=True)
